package com.text.controller;

import com.github.pagehelper.PageInfo;
import com.text.entity.Orders;
import com.text.service.OrdersService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


/**
 * (Orders)表控制层
 *
 * @author makejava
 * @since 2023-06-25 17:12:39
 */
@RestController
@RequestMapping("/admin")
public class OrdersController {
    /**
     * 服务对象
     */
    @Resource
    private OrdersService ordersService;

    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 分页查询
     *
     * @param orders 筛选条件

     * @return 查询结果
     */
    @GetMapping("/ordersList")
    public ResponseEntity<PageInfo<Orders>> queryByPage(@RequestBody(required = false) Orders orders,
                                                        @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize) {
        PageInfo<Orders> ordersListPage = this.ordersService.queryByPage(orders,pageNum,pageSize);
        return ResponseEntity.ok(ordersListPage);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/wy/{id1}")
    public ResponseEntity<Orders> queryById(@PathVariable("id1") Integer id) {
        Object object = redisTemplate.opsForValue().get("order_" + id);
        if (object != null) {
            return ResponseEntity.ok((Orders) object);
        }
        Orders order = this.ordersService.queryById(id);
        redisTemplate.opsForValue().set("order_" + id,order,1, TimeUnit.DAYS);
        return ResponseEntity.ok(order);
    }

    /**
     * 新增数据
     *
     * @param orders 实体
     * @return 新增结果
     */
    @PostMapping("/addorders")
    public ResponseEntity<Orders> add(@RequestBody Orders orders) {
        return ResponseEntity.ok(this.ordersService.insert(orders));
    }

    /**
     * 编辑数据
     *

     * @return 编辑结果
     */
    @PutMapping("/editorders")
    public ResponseEntity<Orders> edit(@RequestBody Orders orders) {
        Orders u = this.ordersService.update(orders);
        redisTemplate.opsForValue().set("order_" + orders.getId(),u);
        return ResponseEntity.ok(u);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/deleteorders")
    public ResponseEntity<Boolean> deleteById(Integer id) {
        boolean f =this.ordersService.deleteById(id);
        redisTemplate.delete("order_" + id);
        return ResponseEntity.ok(f);
    }

}

